/**
 * @description 存放方法的hook
 * @author fzl
 */

import { userSignApi, userLoginApi } from "@/api/login";
import { getCurrentInstance } from "vue"
import { IResultOr } from "@/api/interface";
import { key, useStore } from "@/store";
import { useRoute } from "vue-router"

interface IRuleForm {
    mobile: string;
    password: string;
}

export default function useFormOperates(router: any, params: IRuleForm) {
    const { proxy }: any = getCurrentInstance(); //获取上下文
    const store = useStore()
    const route = useRoute()

    //TODO:注册接口
    function userSign(params: IRuleForm) {
        userSignApi(params).then((res: IResultOr) => {
            const { success, message } = res;
            if (success) {
                proxy.$message.success(message);
            } else {
                proxy.$message.error(message);
            }
        });
    }
    //TODO:登录接口
    function userLogin(params: IRuleForm) {
        userLoginApi(params).then((res: IResultOr) => {
            const { success, message, result } = res;
            console.log(res);
            let { status, userId } = result
            if (success) {
                // 本地保存登录状态码status
                localStorage.setItem("userId", userId)
                store.commit("setUserStatus", status)
                const { redirect }: any = route.query
                router.push({ path: redirect || '/home' })
                // window.location.href = '/home'
                proxy.$message.success(message);
            } else {
                proxy.$message.error(message);
            }
        })
    }

    return {
        userSign,
        userLogin
    }

}
